package cn.tedu.order.service.impl;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.service.OrderService;
import cn.tedu.order.tcc.OrderTccAction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 订单具体操作
 *
 * @author 郭鲁政
 */

@Service
@GlobalTransactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderTccAction orderTccAction;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private StorageClient storageClient;

    @Override
    public void create(Order order) {
        //TODO:远程调用发号器,获取订单ID
        String orderId = easyIdClient.nextId("order_business");
        Long aLong = Long.valueOf(orderId);
        //TODO:临时随机产生一个id,添加发号器之后,删除这行代码

        order.setId(aLong);

        /**
         * 第一个参数上下文对象,在tcc的动态代理对象中,通过AOP 添加了前置通知,
         * 在前置代码中会创建上下文对象
         * 此时 orderTccAction 是一个动态代理对象
         * 第二阶段由 orderTccAction事务处理器调用
         */
        orderTccAction.prepare(null,order.getId(),order.getUserId(),order.getProductId(),order.getCount(),order.getMoney());
//        TODO:远程调用库存,减少库存
        storageClient.decrease(order.getProductId(),order.getCount());
        //TODO:远程调用账户,扣减账户
        accountClient.decrease(order.getUserId(), order.getMoney());
    }
}
